import config from '@/config'
import axios from 'axios'
import { getLocal } from '@/utils/local'

class HttpRequest {
  constructor() {
    this.baseURL = config.baseURL;
    this.timeout = 3000;
  }
  setInterceptors(instance) { //创建单独的拦截器
    instance.interceptors.request.use(config => {
      config.headers.authorization = 'Bearer ' + getLocal('token')
      return config;
    });
    instance.interceptors.response.use(res => {
      if(res.status === 200){
        if(res.data.err === 0) {
          return Promise.resolve(res.data);
        }else{
          return Promise.reject(res.data.data);
        }
      }else {
        return Promise.reject(res.data.data);
      }
    }, err => {
      switch (err.response.status) {
        case '401':
          console.log(err);
          break;
        default:
          break;
      }
      return Promise.reject(err);
    })
  }
  mergeOption(options) {
    return { baseURL: this.baseURL, timeout: this.timeout, ...options };
  }
  request(options) {
    const instance = axios.create();
    this.setInterceptors(instance);
    const opts = this.mergeOption(options);
    return instance(opts);
  }
  get(url, config) {
    return this.request({
      method: 'get',
      url,
      ...config
    })
  }
  post(url, data) {
    return this.request({
      method: 'post',
      url,
      data: data
    })
  }
}

export default new HttpRequest;